package cn.spream.jstudy.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created with IntelliJ IDEA.
 * User: sjx
 * Date: 14-7-17
 * Time: 下午6:03
 * To change this template use File | Settings | File Templates.
 */
public class SemaphorePool {

    private final List<String> strings = new ArrayList<String>();
    private final Semaphore semaphore;
    private final Lock lock = new ReentrantLock();

    public SemaphorePool(int size) {
        init(size);
        this.semaphore = new Semaphore(size);
    }

    private void init(int size) {
        for (int i = 0; i < size; i++) {
            strings.add("第" + (i + 1) + "个元素");
        }
    }

    /**
     * 获取资源
     *
     * @return
     */
    public String get() {
        try {
            System.out.println("等待获取资源");
            semaphore.acquire();
            String string = strings.remove(0);
            System.out.println("获取资源成功：" + string);
            return string;
        } catch (InterruptedException e) {

        }
        return null;
    }

    /**
     * 归还资源
     * @param string
     */
    public void add(String string) {
        System.out.println("等待回收资源：" + string);
        semaphore.release();
        lock.lock();
        int size = 0;
        try {
            strings.add(string);
            size = strings.size();
        } finally {
            lock.unlock();
        }
        System.out.println("资源回收成功：" + string + ",目前资源总数：" + size);
    }

}
